package com.ruoyi.framework.security.service

import com.ruoyi.common.constant.*
import com.ruoyi.common.exception.user.CaptchaException
import com.ruoyi.common.exception.user.CaptchaExpireException
import com.ruoyi.common.utils.*
import com.ruoyi.framework.manager.AsyncManager
import com.ruoyi.framework.manager.factory.AsyncFactory
import com.ruoyi.framework.redis.RedisCache
import com.ruoyi.framework.security.RegisterBody
import com.ruoyi.project.system.domain.SysUser
import com.ruoyi.project.system.service.ISysConfigService
import com.ruoyi.project.system.service.ISysUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

/**
 * 注册校验方法
 *
 * @author ruoyi
 */
@Component
class SysRegisterService {
    @Autowired
    private val userService: ISysUserService? = null

    @Autowired
    private val configService: ISysConfigService? = null

    @Autowired
    private val redisCache: RedisCache? = null

    /**
     * 注册
     */
    fun register(registerBody: RegisterBody): String {
        var msg = ""
        val username = registerBody.username!!
        val password = registerBody.password!!
        val captchaEnabled = configService!!.selectCaptchaEnabled()
        // 验证码开关
        when {
            captchaEnabled -> {
                validateCaptcha(username, registerBody.code!!, registerBody.uuid!!)
            }
        }
        when {
            StringUtils.isEmpty(username) -> {
                msg = "用户名不能为空"
            }
            StringUtils.isEmpty(password) -> {
                msg = "用户密码不能为空"
            }
            username.length < UserConstants.USERNAME_MIN_LENGTH || username.length > UserConstants.USERNAME_MAX_LENGTH -> {
                msg = "账户长度必须在2到20个字符之间"
            }
            password.length < UserConstants.PASSWORD_MIN_LENGTH || password.length > UserConstants.PASSWORD_MAX_LENGTH -> {
                msg = "密码长度必须在5到20个字符之间"
            }
            UserConstants.NOT_UNIQUE == userService!!.checkUserNameUnique(username) -> {
                msg = "保存用户'$username'失败，注册账号已存在"
            }
            else -> {
                val sysUser = SysUser()
                sysUser.userName = username
                sysUser.nickName = username
                sysUser.password = SecurityUtils.encryptPassword(registerBody.password)
                val regFlag = userService.registerUser(sysUser)
                if (!regFlag) {
                    msg = "注册失败,请联系系统管理人员"
                } else {
                    AsyncManager.me().execute(
                        AsyncFactory.recordLogininfor(
                            username, Constants.REGISTER,
                            MessageUtils.message("user.register.success")
                        )
                    )
                }
            }
        }
        return msg
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    fun validateCaptcha(username: String?, code: String, uuid: String) {
        val verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "")
        val captcha = redisCache!!.getCacheObject(verifyKey)
        redisCache.deleteObject(verifyKey)
        if (captcha == null) {
            throw CaptchaExpireException()
        }
        if (code != captcha) {
            throw CaptchaException()
        }
    }
}
